///<reference path="../../services/jquery.d.ts"/>
import {
  Component
} from '@angular/core';
import {
  NavController,
  NavParams,
  AlertController,
  ModalController,
  LoadingController,
  ToastController, ViewController
} from 'ionic-angular';
import {
  Http,
  Headers,
  RequestOptions,
  URLSearchParams
} from '@angular/http';
import {
  baseCommon
} from '../../common/baseCommon';
import {
  AppConfig
} from './../../app/app.config';
import {
  Storage
} from '@ionic/storage'
import {
  GroupsUtil
} from '../../common/CommonUtil'

/**
 * Generated class for the GroupPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-group',
  templateUrl: 'group.html',
})

export class GroupPage{
  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public alertCtrl: AlertController,
              public modalCtrl: ModalController,
              public loadingCtrl: LoadingController,
              public http: Http,
              public viewCtrl: ViewController,
              public toastCtrl: ToastController,
              public storage: Storage) {
  }

  listData: any;
  groupList = [];
  ifSuccess: boolean = false;
  aim: any;
  date: any;
  location: any;
  maxPerson: number;

  ionViewDidLoad() {

    this.storage.get('sessionID').then(val => {
      this.getNearGroup(AppConfig.httpLoc + '/group/nearGroup?sessionID=' + val);
    })

  }

  /**
   * 加入圈子
   *
   * @param {any} id
   * @memberof GroupPage
   */
  joinGroup(id) {
    this.storage.get('sessionID').then(val => {
      this.joinGroupRequest(AppConfig.httpLoc + '/group/join', id, val);
    })
  }

  /**
   * 下拉刷新
   *
   * @param {any} refresher
   * @memberof GroupPage
   */
  doRefresh(refresher) {
    this.storage.get('sessionID').then(val => {
      this.getNearGroupRef(AppConfig.httpLoc + '/group/nearGroup?sessionID=' + val, refresher);
    })
  }


  /**
   * 发布圈子弹框
   *
   * @memberof GroupPage
   */
  showPrompt() {
    let prompt = this.alertCtrl.create({
      title: '发布圈子',
      message: "快快发布一个圈子，寻找你的朋友吧！！",
      inputs: [
        {
          name: 'name',
          placeholder: '在此输入圈子名字..'
        },
        {
          name: 'aim',
          placeholder: '在此输入圈子描述..'
        },
        {
          name: 'datetime',
          type: 'datetime-local',
          placeholder: '请在此填写活动时间..'
        },
        {
          name: 'loc',
          placeholder: '请在此填写活动地点..'
        },
        {
          name: 'maxPerson',
          placeholder: '请在此填写需要的人数..'
        },
      ],
      buttons: [{
        text: '我再想想',
        handler: data => {

        }
      },
        {
          text: '立刻发布',
          handler: data => {
            this.storage.get('sessionID').then(val => {
              if (data.name != '' && data.aim != '' && data.datetime != '' && data.loc != '' && data.maxPerson != '') {
                this.addGroupRequest(AppConfig.httpLoc + '/group/add', data.name, data.aim, data.datetime, data.loc, data.maxPerson, val);
              } else {
                baseCommon.showToast(this.toastCtrl, '所有项均为必填项！');
              }
              // this.addGroupRequest(AppConfig.httpLoc + '/group/add',data.name, data.aim, data.datetime,data.loc, data.maxPerson, val);
            });
          }
        }
      ]
    });
    AppConfig.viewCtrl = prompt;
    prompt.onDidDismiss(data => {
      AppConfig.viewCtrl = null;
    })
    // console.log('viewCtrl in group '+AppConfig.viewCtrl)
    prompt.setCssClass("groupAlert");
    prompt.present();
  }

  
  MaxPerson() {
    let prompt = this.alertCtrl.create({
      title: '人数已满',

      buttons: [{
        text: '确定',
        handler: data => {

        }
      },
      ]
    });
    prompt.present();
  }


  /**
   * 得到附近的圈子
   *
   * @param {any} apiUrl
   * @memberof GroupPage
   */
  getNearGroup(apiUrl) {
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded',
    });

    let options = new RequestOptions({
      headers: headers,
    });

    this.http.get(apiUrl, options)
      .toPromise()
      .then(data => {
        this.groupList = data.json().data;
        this.ifSuccess = true;
      }, err => {
        console.log(err);
      })
  }

  /**
   * 下拉得到附近的圈子
   *
   * @param {any} apiUrl
   * @param {any} refresher
   * @memberof GroupPage
   */
  getNearGroupRef(apiUrl, refresher) {
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded',
    });

    let options = new RequestOptions({
      headers: headers,
    });

    this.http.get(apiUrl, options)
      .toPromise()
      .then(data => {
        setTimeout(() => {
          this.groupList = data.json().data;
          refresher.complete();
        }, 1000);
      }, err => {
        console.log(err);
      })
  }


  /**
   * 添加圈子
   *
   * @param {any} apiUrl
   * @memberof GroupPage
   */
  addGroupRequest(apiUrl, name, aim, datetime, location, maxPerson, sessionID) {
    let loading = baseCommon.showLoading(this.loadingCtrl, '圈子发布中....')
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded',
    });

    let options = new RequestOptions({
      headers: headers,
    });

    let pramas: URLSearchParams = new URLSearchParams();

    pramas.set('name', name);
    pramas.set('aim', aim);
    pramas.set('datetime', datetime);
    pramas.set('location', location);
    pramas.set('maxPerson', maxPerson);
    pramas.set('sessionID', sessionID);

    console.log('发送新建群组请求')
    this.http.post(apiUrl, pramas, options)
      .toPromise()
      .then(data => {
        console.log(data)
        var group = JSON.parse(String(data['_body'])).data;
        GroupsUtil.add(group);    //更新Group
        this.listData = data.json();
        if (data.json().message == '存在敏感词汇') {
          baseCommon.showToast(this.toastCtrl, '存在敏感词汇..');
        }
        // console.log(this.listData);
        loading.dismiss();
      }, err => {
        console.log(err);
      })
  }

  /**
   * 加入圈子
   *
   * @param {any} apiUrl
   * @memberof GroupPage
   */
  joinGroupRequest(apiUrl, groupid, sessionID) {
    let loading = baseCommon.showLoading(this.loadingCtrl, '正在走上人生巅峰....')
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded',
    });

    let options = new RequestOptions({
      headers: headers,
    });

    let pramas: URLSearchParams = new URLSearchParams();

    pramas.set('id', groupid);
    pramas.set('sessionID', sessionID);
    this.http.post(apiUrl, pramas, options)
      .toPromise()
      .then(data => {
        var group = JSON.parse(String(data['_body'])).data;
        GroupsUtil.add(group);    //更新Group
        loading.dismissAll();
        this.groupList.forEach(val=>{
          if(val.id == groupid){
            val.joined = true;
          }
        })
        this.ifSuccess = true;
      }, err => {
        console.log(err);
      })
  }

}
